package com.site.blog.my.core.controller.admin;

import com.site.blog.my.core.config.Constants;
import com.site.blog.my.core.dao.AdminUserMapper;
import com.site.blog.my.core.entity.FilePo;
import com.site.blog.my.core.service.impl.FileServiceImpl;
import com.site.blog.my.core.util.MyBlogUtils;
import com.site.blog.my.core.util.PageQueryUtil;
import com.site.blog.my.core.util.Result;
import com.site.blog.my.core.util.ResultGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.UUID;


@Controller
@RequestMapping("/admin")
public class UploadController {

    @Resource
    private FileServiceImpl fileService;

    @Resource
    private AdminUserMapper adminUserMapper;

    @PostMapping({"/upload/file"})
    @ResponseBody
    public Result upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        File fileDirectory = new File(Constants.FILE_UPLOAD_DIC);
        //创建文件
        File destFile = new File(Constants.FILE_UPLOAD_DIC + newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            Result resultSuccess = ResultGenerator.genSuccessResult();
            resultSuccess.setData(MyBlogUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" + newFileName);
            return resultSuccess;
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("文件上传失败");
        }
    }

    @PostMapping({"/save/file"})
    public String saveFile(HttpSession session, @RequestParam("file") MultipartFile file) throws URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        File fileDirectory = new File(Constants.FILE_UPLOAD_DIC);
        //创建文件
        File destFile = new File(Constants.FILE_UPLOAD_DIC + newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);

            FilePo filePo = new FilePo();
            Integer loginUserId = Integer.valueOf(session.getAttribute("loginUserId").toString());
            filePo.setCreateUser(loginUserId);
            filePo.setTitle(newFileName);
            filePo.setPath(Constants.FILE_UPLOAD_DIC + newFileName);
            filePo.setType(suffixName);
            fileService.insert(filePo);
            return "redirect:/admin/file";
        } catch (IOException e) {
            e.printStackTrace();
            return "admin/login";
        }
    }

    @GetMapping("/file/list")
    @ResponseBody
    public Result list(@RequestParam Map<String, Object> params, HttpSession session) {
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        Integer loginUserId = Integer.valueOf(session.getAttribute("loginUserId").toString());
        if(loginUserId!=1){
            params.put("loginUserId",loginUserId);
        }
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(fileService.getFilesPage(pageUtil));
    }

    @PostMapping("/file/download")
    @ResponseBody
    public Result download(@RequestBody Integer[] ids, HttpServletResponse response) {

        FilePo filePo = adminUserMapper.getFile(ids[0]);
        File file = new File(filePo.getPath());

        try {
//            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filePo.getPath(), "UTF-8"));

            FileInputStream fis = null;
            String downloadDir = "D:\\deploy\\download\\";
            File downloadFile = new File(downloadDir+filePo.getTitle());
            OutputStream fos = new FileOutputStream(downloadFile);

            if (file.exists()) {
                fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

            }
            fis.close();
            fos.close();
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("下载失败");
        }

    }

}
